package com.yangtu.nearbyshop.admin.job;

import com.yangtu.nearbyshop.admin.service.AdminOrderService;
import com.yangtu.nearbyshop.db.domain.*;
import com.yangtu.nearbyshop.db.service.NearbyshopCouponService;
import com.yangtu.nearbyshop.db.service.NearbyshopCouponUserService;
import com.yangtu.nearbyshop.db.service.NearbyshopGrouponRulesService;
import com.yangtu.nearbyshop.db.service.NearbyshopGrouponService;
import com.yangtu.nearbyshop.db.service.itf.INearbyshopOrderService;
import com.yangtu.nearbyshop.db.util.CouponConstant;
import com.yangtu.nearbyshop.db.util.CouponUserConstant;
import com.yangtu.nearbyshop.db.util.OrderUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 检测优惠券过期情况
 */
@Component
public class GrouponJob {
    private final Log logger = LogFactory.getLog(GrouponJob.class);

    @Autowired
    private NearbyshopGrouponService grouponService;
    @Autowired
    private NearbyshopGrouponRulesService rulesService;

    @Autowired
    private INearbyshopOrderService orderService;

    @Autowired
    private AdminOrderService adminOrderService;

    /**
     * 每隔5分钟检查
     */
    @Scheduled(fixedDelay = 5 * 60 * 1000)
    public void checkCouponExpired() {
        logger.info("系统开启任务-检查团购是否已经过期");
        List<NearbyshopGrouponRules> couponList = rulesService.queryExpired();
        for(NearbyshopGrouponRules coupon : couponList){
            List<NearbyshopGroupon> grouops = grouponService.queryByRules(coupon.getId());
            if(grouops.size() < coupon.getDiscountMember()){
                for(NearbyshopGroupon goup : grouops){
                    adminOrderService.refundGroup(goup.getOrderId());
//                   adminOrderService.refundGroupNative(goup.getOrderId());
                }

                coupon.setStatus(2);
                rulesService.updateById(coupon);
            }else {
                coupon.setStatus(1);
                rulesService.updateById(coupon);
            }
        }
        logger.info("系统结束任务-检查团购是否已经过期");
    }

}
